<template>
    <el-table ref="table" :data="props.data" table-layout="auto" size="small" border class="table"
        @cell-click="croodClick" highlight-current-row @current-row-key="currentRowKey">
        <el-table-column label="X轴">
            <template #default="scope">
                <el-input-number v-model="scope.row.x" size="small" :precision="3" controls-position="right"
                    placeholder="请输入X轴" @change="croodChange(scope.$index, scope.row)" />
            </template>
        </el-table-column>
        <el-table-column label="Y轴">
            <template #default="scope">
                <el-input-number v-model="scope.row.y" size="small" :precision="3" controls-position="right"
                    placeholder="请输入Y轴" @change="croodChange(scope.$index, scope.row)" />
            </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
            <template #default="scope">
                <el-button type="success" :icon="Plus" size="small" circle @click="addCrood(scope.$index)" />
                <el-button type="danger" :icon="Close" size="small" circle @click="DeleteCrood(scope.$index)" />
            </template>
        </el-table-column>
    </el-table>
</template>

<script lang='ts' setup>
import { ref, watch } from 'vue'
import { message } from "@/utils/message";
import { Plus, Close } from '@element-plus/icons-vue'
import { useMapStoreHook } from "@/store/modules/map";
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router';
import {
    initKonvaStage,
    mouseCorrd,
    stage,
    layer,
    initScale
} from "@/views/home/components/dxfMap";

const pureMap = useMapStoreHook()
const { crossDetail, crossIndex, crossInsert } = storeToRefs(pureMap)
const props = defineProps({
    data: {
        type: Array<any>,
        required: true,
        default: [{}]
    }
})

var isDrawMap = ref(false)

// 监听路由
const route = useRoute()
watch(() => route.path, (newValue) => {
    if (newValue === '/road/index')
        isDrawMap.value = false
    else
        isDrawMap.value = true
}, { immediate: true })

const table = ref(null)

// 坐标修改时
function croodChange(i, val) {
    const crossName = pureMap.crossDetail.name
    if (!isDrawMap.value) return false;  //在路段页面下面代码不执行
    // 根据当前路由路径判断是哪个类型的元素，并生成相应的选择器
    const name = route.path === '/jobRegion/index' ? `.job-${crossName}` : `.cross-${crossName}`
    // 在Konva的舞台上找到对应类型的元素，并获取第一个元素
    // 然后在第一个元素中找到类名为'circle'的子元素，并获取第i个元素
    const targetCircle = pureMap.stageKonva.find(name)[0].find('.circle')[i]
    // 在第一个元素中找到类名为'line'的子元素，并获取第一个元素
    const targetLine = pureMap.stageKonva.find(name)[0].find('.line')[0]
    // 获取目标圆圈的初始缩放比例
    const { initScale } = targetCircle.attrs
    // 设置目标圆圈的x坐标，根据传入的值和初始缩放比例计算
    targetCircle.x(val.x * initScale)
    // 设置目标圆圈的y坐标，根据传入的值和初始缩放比例计算
    targetCircle.y(val.y * initScale)
    // 更新目标线条的顶点坐标，根据传入的值和初始缩放比例计算
    // splice方法用于替换数组中的元素，这里替换第i个和第i+1个元素
    targetLine.points().splice(i, 2, val.x * initScale, val.y * initScale)
}

// 新增交管坐标
function addCrood(i) {
    table.value.data.splice(i + 1, 0, {})
}

// 删除交管坐标
function DeleteCrood(i) {
    if (table.value.data.length === 1) {
        table.value.data.splice(i, 1, {})
        message(`最后一条数据不能删除！`, {
            type: "error"
        });
    } else {
        table.value.data.splice(i, 1)
    }
    // 删除时一并删除地图中的交管数据及pinia中的交管数据
    const crossName = crossDetail.value.name
    if (!isDrawMap.value || crossName === "") return false;
    const name = route.path === '/jobRegion/index' ? `.job-${crossName}` : `.cross-${crossName}`
    const targetCircle = pureMap.stageKonva.find(name)[0].find('.circle')[i]
    const targetLine = pureMap.stageKonva.find(name)[0].find('.line')[0]
    if (!targetCircle) return false;
    targetCircle.destroy()
    targetLine.points().splice(i * 2, 2)
}



const currentRowKey = ref(0)
// 获取所有 Circle 实例
const circles = layer.find('Circle'); // 使用选择器过滤
// 选中坐标节点高亮
const croodClick = (row, column, cell) => {
    currentRowKey.value = table.value.data.indexOf(row)
    // console.log('选中的行数据：', row);
    if (Object.keys(row).length === 0) {
        pureMap.$patch({
            crossInsert: true,
            crossIndex: currentRowKey.value
        })
    } 

    // 目标坐标
    const targetPoint = { x: row.x * 100 * initScale, y: row.y * 100 * initScale };
    circles.forEach((circle) => {
        circle.moveToTop()
        // 获取圆心和半径
        const centerX = circle.x();
        const centerY = circle.y();
        const radius = circle.radius();
        // 计算点到圆心的距离
        const distance = Math.sqrt(
            Math.pow(targetPoint.x - centerX, 2) + Math.pow(targetPoint.y - centerY, 2)
        );
        // 判断是否在圆内（可扩展为包含边框）
        if (distance <= radius) {
            // console.log('找到匹配的 Circle:', circle);
            // 改变颜色
            circle.fill('yellow');
        } else {
            // circle.fill('red');
            if (+circle.parent.attrs.id == row.crossid) {
                circle.fill('#A6290C');
            }
        }

    });

}

</script>

<style lang="scss" scoped></style>